import { NextRequest, NextResponse } from 'next/server'
import { getUserFromRequest } from '@/lib/auth'
import AliyunOSSService from '@/lib/aliyunOSS'

export async function POST(request: NextRequest) {
  try {
    const user = await getUserFromRequest(request)
    
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const body = await request.json()
    const { maxAge = 24 * 60 * 60 * 1000 } = body // 默认24小时

    try {
      const ossService = new AliyunOSSService()
      const deletedCount = await ossService.cleanupExpiredFiles('sensevoice-audio', maxAge)
      
      return NextResponse.json({
        success: true,
        message: `清理了 ${deletedCount} 个过期文件`,
        deletedCount
      })
    } catch (error) {
      console.error('OSS cleanup error:', error)
      return NextResponse.json({
        success: false,
        error: error instanceof Error ? error.message : 'OSS服务未配置或配置错误'
      }, { status: 500 })
    }

  } catch (error) {
    console.error('Cleanup API error:', error)
    return NextResponse.json(
      { error: '清理失败' },
      { status: 500 }
    )
  }
}

export async function GET(request: NextRequest) {
  try {
    const user = await getUserFromRequest(request)
    
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    // 检查OSS配置状态
    try {
      const ossService = new AliyunOSSService()
      return NextResponse.json({
        success: true,
        configured: true,
        message: 'OSS服务配置正常'
      })
    } catch (error) {
      return NextResponse.json({
        success: false,
        configured: false,
        error: error instanceof Error ? error.message : 'OSS服务未配置'
      })
    }

  } catch (error) {
    console.error('OSS status check error:', error)
    return NextResponse.json(
      { error: '检查失败' },
      { status: 500 }
    )
  }
}
